package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author zqc
 * @since 2024-08-21
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {
    @Autowired
    private AdUserMapper adUserMapper;
    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        Map<String,Object> map = new HashMap<>();

        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName,dto.getName());
        AdUser adUser = adUserMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(adUser)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String salt = adUser.getSalt();
        String inputPs = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if(!inputPs.equals(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        adUser.setPassword("");
        adUser.setSalt("");
        map.put("user",adUser);
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        return ResponseResult.okResult(map);
    }
}
